#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class HenanShangqiuPolicy(BaseTaxPolicySpider):
    name = 'henan_shangqiu_policy'
    
    province = '河南省'
    city = '商丘市'
    # county = '滑县'
    park = ''

    def start_requests(self):
        for source, county, url in [
            ['商丘市人民政府', "", "https://www.shangqiu.gov.cn/zwgk/zc47szfbgs/hzgfxwj"],
            ['商丘市人民政府', "", "https://www.shangqiu.gov.cn/zwgk/zc47szfbgs/sz47szfbgs"],
            ['商丘市人民政府', "", "https://www.shangqiu.gov.cn/zwgk/zc47szfbgs/szw47szfbgs"],
            ['商丘市人民政府', "", "https://www.shangqiu.gov.cn/zwgk/zc47szfbgs/szr47szfbgs"],
            ['商丘市人民政府', "", "https://www.shangqiu.gov.cn/zwgk/zc47szfbgs/szt47szfbgs"],
            ['商丘市人民政府', "", "https://www.shangqiu.gov.cn/zwgk/zc47szfbgs/szb47szfbgs"],
            ['商丘市人民政府', "", "https://www.shangqiu.gov.cn/zwgk/zc47szfbgs/szbw47szfbgs"],
            ['商丘市发展和改革委员会', "", "https://fgw.shangqiu.gov.cn/zwgk/zc/hzgfxwj"],
            ['商丘市发展和改革委员会', "", "https://fgw.shangqiu.gov.cn/zwgk/zc/zcfg33sqsfzhggwyh"],
            ['商丘市发展和改革委员会', "", "https://fgw.shangqiu.gov.cn/zwgk/zc/bmwj33sqsfzhggwyh"],
            ['商丘市工业和信息化局', "", "https://gxj.shangqiu.gov.cn/zwgk/zc/gfxwj19sqsgyhxxhj"],
            ['商丘市工业和信息化局', "", "https://gxj.shangqiu.gov.cn/zwgk/zc/qtwj19sqsgyhxxhj"],
            ['商丘市科学技术局', "", "https://kjj.shangqiu.gov.cn/zwgk/zc/zcfg11sqskxjsj"],
            ['商丘市科学技术局', "", "https://kjj.shangqiu.gov.cn/zwgk/zc/bmwj11sqskxjsj"],
            ['商丘市人力资源和社会保障局', "", "https://rsj.shangqiu.gov.cn/zwgk/zc/hzgfxwj"],
            ['商丘市人力资源和社会保障局', "", "https://rsj.shangqiu.gov.cn/zwgk/zc/bmwj35sqsrlzyhshbzj"],
            ['商丘市住房和城乡建设局', "", "https://zjj.shangqiu.gov.cn/zwgk/zc/hzgfxwj"],
            ['商丘市住房和城乡建设局', "", "https://zjj.shangqiu.gov.cn/zwgk/zc/bmwj5sqszfhcxjsj"],
            ['商丘市农业农村局', "", "https://nyncj.shangqiu.gov.cn/zwgk/zc/gfxwj3sqsnyncj"],
            ['商丘市农业农村局', "", "https://nyncj.shangqiu.gov.cn/zwgk/zc/qtwj3sqsnyncj"],
            ['商丘市商务局', "", "https://swj.shangqiu.gov.cn/zwgk/zc/gfxwj14sqsswj"],
            ['商丘市商务局', "", "https://swj.shangqiu.gov.cn/zwgk/zc/qtwj14sqsswj"],
            ['商丘市市场监督管理局', "", "https://scjgj.shangqiu.gov.cn/zwgk/zc/gfxwj12sqsscjdglj"],
            ['商丘市市场监督管理局', "", "https://scjgj.shangqiu.gov.cn/zwgk/zc/qtwj12sqsscjdglj"],
            ['商丘市财政局', "", "https://czj.shangqiu.gov.cn/zwgk/zc/hzgfxwj"],
            ['商丘市财政局', "", "https://czj.shangqiu.gov.cn/zwgk/zc/bmwj20sqsczj"],
            ['商丘市商城县文化广电和旅游局', "", "https://whgdlyj.shangqiu.gov.cn/zwgk/zc/zcfg10sqswhgdhlyj"],
            ['商丘市商城县文化广电和旅游局', "", "https://whgdlyj.shangqiu.gov.cn/zwgk/zc/bmwj10sqswhgdhlyj"],
        ]:
            timestrip = int(time.time())
            cookies = {
                'TWAF_AR': f'{timestrip}:2407892011'
            }
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={'item': item}, dont_filter=True, cookies=cookies)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        elem_list = response.xpath(
            "//div[@class='page_list' or @class='article-list' or @class='bd']//li//a[(contains(@href, '.htm') or @title)]/ancestor::li[string-length(string(.))>=10] | "
            "//ul[contains(@class, 'ul ULLIST') or @class='infoList']//li//a[@title]/ancestor::li[string-length(string(.))>=10]"
        )
        if not elem_list:
            cookies = {
                'TWAF_AR': f'{int(time.time())}:2407892011'
            }
            yield response.follow(response.url, callback=self.parse_list, meta={'item': prev_item}, dont_filter=True,
                                  cookies=cookies)
            return
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a[@title]/@href""").get()
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            # if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
            #     continue
            if 'relativeInfo' in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        next_url = response.xpath("""//a[text()='下页' or .//text()='下一页' or text()='»']/@href""").get()
        if next_url and next_url not in ['javascript:void(0);']:
            cookies = {
                'TWAF_AR': f'{int(time.time())}:2407892011'
            }
            # url = response.url.split(next_url.split('/')[0])[0] + next_url
            print(response.url, 'next', next_url)
            yield response.follow(next_url, callback=self.parse_list, meta={'item': prev_item}, dont_filter=True, cookies=cookies)
        else:
            # print('ERROR----', response.text)
            print(response.url, 'not next_url')

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("//*[contains(.//text(), '发布日期：') or contains(.//text(), '发布时间：')]//text()").re_first(r"(\d{4}-\d{1,2}-\d{1,2})")
        # print(item['publish_date'])
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        # print(item['content'])
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl henan_shangqiu_policy".split())
